Converting an array to hash using Hash::[] constructor
The Hash::[] constructor method creates a hash directly from an array where each pair of elements in the array is treated as a key-value pair.
Syntax:
Hash[*array]
Example: In this example,we convert an array into a hash , where each element in the array is transformed into a key-value pair using Hash::[] constructor
# Define an array with elements representing key-value pairs
array = [:a, 1, :b, 2, :c, 3]
# Convert an array into a hash Using Hash::[] constructor
# Convert the array directly into a hash using the Hash::[] constructor
hash = Hash[*array]
# Output the resulting hash
puts hash.inspect # Output: {:a=>1, :b=>2, :c=>3}
Output
{:a=>1, :b=>2, :c=>3}
How to convert Array to Hash in Ruby?
In this article, we will discuss how to convert an array to a hash in Ruby. Converting an array to a hash can be useful when we have data in an array format and need to organize it into key-value pairs for easier access and manipulation.
Table of Content
- Converting array to hash using Hash::[] constructor
- Converting array to hash using Array#each_slice
- Converting array to hash using Hash#[] with a block